830. Prime numbers

 

Print all prime numbers in the range from m to n, inclusive.

 

Input. Two positive integers m and n (2 ≤ mn ≤ 300000).

 

Output. Print all prime numbers in the range [m; n] in ascending order, one number per line. If there are no prime numbers in the range from m to n, print “Absent”.

 

Sample input 1

Sample output 1

2 5

2

3

5

 

 

Sample input 2

Sample output 2

4 4

Absent

 

 

ÐÅØÅÍÈÅ

prime test

 

Algorithm analysis

Iterate through all positive integers in the range from m to n and print only the prime numbers. If there are no prime numbers in the range [m; n], print the message “Absent.”

 

Algorithm implementation

The function IsPrime checks whether the number n is prime.

·        If n is prime, the function returns 1.

·        Otherwise, the function returns 0.

 

int IsPrime(int n)

{

  for(int i = 2; i <= sqrt(n); i++)

    if (n % i == 0) return 0;

  return 1;

}

 

The main part of the program. Read the input data.

 

scanf("%d %d",&m,&n);

 

Initially, assume that there are no prime numbers in the range. Set flag = 0.

 

flag = 0;

 

Iterate through the numbers from m to n. If the current number is prime, print it and set flag = 1.

 

for(i = m; i <= n; i++)

{

  if (IsPrime(i))

  {

    printf("%d\n",i);         

    flag = 1;

  }

}

 

If no prime number is printed (flag = 0), print the message “Absent”.

 

if (flag == 0) puts("Absent");

 

Python implementation

 

import math

 

The function IsPrime checks whether the number n is prime.

·        If n is prime, the function returns 1.

·        Otherwise, the function returns 0.

 

def IsPrime(n):

  for i in range(2, int(math.sqrt(n)) + 1):

    if n % i == 0: return False

  return True

 

The main part of the program. Read the input data.

 

m, n = map(int,input().split())

 

Initially, assume that there are no prime numbers in the range. Set flag = 0.

 

flag = 0

 

Iterate through the numbers from m to n. If the current number is prime, print it and set flag = 1.

 

for i in range(m, n + 1):

  if IsPrime(i):

    print(i)

    flag = 1

 

If no prime number is printed (flag = 0), print the message “Absent”.

 

if flag == 0: print("Absent")